package com.vanke.devops.api.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vanke.core.json.CustomObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

/**
 * @author 陈景阳
 * @since 2018/1/10
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/api");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.addAll(messageConverters());
    }

    private List<HttpMessageConverter<?>> messageConverters() {
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        jsonConverter.setObjectMapper(createDefaultObjectMapper());
        messageConverters.add(jsonConverter);
        return messageConverters;
    }

    private ObjectMapper createDefaultObjectMapper() {
        CustomObjectMapper mapper = new CustomObjectMapper();
        mapper.setCamelCaseToLowerCaseWithUnderscores(false);
        mapper.setDateFormatPattern("yyyy-MM-dd HH:mm:ss");
        mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        mapper.init();
        return mapper;
    }
}
